import time
import ujson as json
import urequests as requests
from window import Window
from questionWindow import Button
from util import display

class CityWindow(Window):
	def __init__(self, city_list):
		Window.__init__(self)

		self.city_list = city_list
		Window.setDrawCB(self, self.cb_draw)

		for i in range(len(self.city_list)):
			btn_city = Button(self.city_list[i], 50, 30 + i * 10, 80, 12)
			btn_city.cb_hold = self.cb_query_weather
			Window.add(self, btn_city)

	def cb_draw(self):
		display.text("City:", 2, 2, 1)

	def run(self):
		Window.run(self)

	def cb_quit(self):
		self.save = 0
		Window.close(self)

	def cb_query_weather(self):
		# 	# 第三步，获取所选城市的当日气温并显示在屏幕上
		city_name = self.hold_title
		print("cb choose and send, index=" + str(city_name))
		temperature = self.query_city_weather(city_name)
		display.fill(0)
		display.text("Temperature:", 10, 10)
		display.text(city_name + ":" + str(temperature), 20, 30)
		display.show()
		time.sleep(3)
		print("City temperature: " + str(temperature))

		Window.close(self)

	def query_city_weather(self, city_name):
		URL = 'http://192.168.4.1:8080/?ask&city_name=' + city_name
		print(URL)
		r = requests.get(URL)
		if r.status_code == 200:
			r_trans = r.text.replace("'", '"')
			r_json = json.loads(r_trans)
			temperature = r_json["result"]
			r.close()
			return temperature